package com.example.user.customviewdemo.camera;

import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Build;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 录像线程
 *
 * @author bcaiw
 *
 */
public class RecordThread extends Thread {

    private MediaRecorder recorder;// 录制视频的类
    private SurfaceHolder surfaceHolder;
    private long recordTime;
    private SurfaceView surfaceview;// 显示视频的控件
    private Camera camera;

    public RecordThread(long recordTime, SurfaceView surfaceview,
                        SurfaceHolder surfaceHolder) {
        this.recordTime = recordTime;
        this.surfaceview = surfaceview;
        this.surfaceHolder = surfaceHolder;
    }

    @Override
    public void run() {

        /**
         * 开始录像
         */
        startRecord();

        /**
         * 启动定时器，到规定时间recordTime后执行停止录像任务
         */
        Timer timer = new Timer();

        timer.schedule(new TimerThread(), recordTime);
    }



    /**
     * 获取摄像头实例对象
     *
     * @return
     */
    public Camera getCameraInstance() {
       /* Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            // 打开摄像头错误
            e.printStackTrace();
            Log.i("info", "打开摄像头错误");
        }
        return c;*/

        Camera c = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                Camera.CameraInfo info = new Camera.CameraInfo();
                Camera.getCameraInfo(i, info);
                if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//这就是前置摄像头，亲。
                    Log.v("tag","打卡前置摄像头");
                    c = Camera.open(i);
                }
            }
        }
        if (c == null) {
            c = Camera.open();
            Log.v("tag","打开后置摄像头");
        }
        return c;
    }

    /**
     * 开始录像
     */
    public void startRecord() {
          this.camera = getCameraInstance();
        camera.setDisplayOrientation(90);
        recorder = new MediaRecorder();
        recorder.reset();
        camera.unlock();
        recorder.setCamera(camera);
        recorder.setPreviewDisplay( surfaceHolder.getSurface());
        recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //recorder.setVideoSize(465,615);
        //recorder.setVideoSize(100,100);
        recorder.setVideoFrameRate(24);
        recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        recorder.setOutputFile("/sdcard/sForm.3gp");
       /* recorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {
                if(what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED){
                    Log.v("tag","录制完成-----------------》");
                }
            }
        });*/
        try {
            recorder.prepare();
            Log.v("tag","prepare()______________________>");
            recorder.start();
        } catch (IOException e) {
            Log.v("tag","prepare erro___________________>");
            e.printStackTrace();
        }
        Log.v("tag","即将start（）");






       /* mediarecorder = new MediaRecorder();// 创建mediarecorder对象
        mCamera = getCameraInstance();
        // 解锁camera
        mCamera.unlock();
        mediarecorder.setCamera(mCamera);

        // 设置录制视频源为Camera(相机)
       // mediarecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        // 设置录制文件质量，格式，分辨率之类，这个全部包括了

       CamcorderProfile profile =  CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
        Log.v("tag","has this QUALITY:"+CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_LOW));
        mediarecorder.setProfile(profile);

        mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
        // 设置视频文件输出的路径
        mediarecorder.setOutputFile("/sdcard/sForm.3gp");
        try {
            // 准备录制
            mediarecorder.prepare();
            // 开始录制
            mediarecorder.start();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
    }

    /**
     * 停止录制
     */
    public void stopRecord() {
        if (recorder != null) {
            // 停止录制
            recorder.stop();
            // 释放资源
            recorder.release();
            recorder = null;

            if(camera!=null){
                camera.release();
                camera = null;
            }
        }
    }

    /**
     * 定时器
     * @author bcaiw
     *
     */
    class TimerThread extends TimerTask {

        /**
         * 停止录像
         */
        @Override
        public void run() {
            stopRecord();
            this.cancel();
        }
    }
}
